package com.erp.order.poa.controller;

import com.activiti.dao.model.Activiti_SubTaskInfoRO;
import com.activiti.dao.model.TaskVo;
import com.activiti.dao.service.ActivitiService;
import com.activiti.dao.service.TaskSubService;
import com.erp.cux.workflow.controller.CuxControllerSupport;
import com.erp.dataset.service.DatasetCommonService;
import com.erp.hr.base.util.CommonUtils;
import com.erp.hr.dao.model.HrDepartment;
import com.erp.hr.dao.model.HrStaffInfoRO;
import com.erp.hr.service.HrCommonService;
import com.erp.masterdata.common.service.MasterDataCommonService;
import com.erp.order.poa.dao.model.*;
import com.erp.order.poa.service.PoAgreementHeadService;
import com.erp.order.poa.service.PoAgreementLineService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.hibernate.exception.ConstraintViolationException;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.util.ShiroUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.*;

@Controller
@RequestMapping("/web/poAgreementHeadAppend")
public class PoAgreementHeadAppendWebController extends CuxControllerSupport {

    //日志处理
    private Logger logger = LoggerFactory.getLogger(PoAgreementHeadAppendWebController.class);

    //服务层注入
    @Autowired
    private PoAgreementHeadService poAgreementHeadService;
    @Autowired
    private PoAgreementLineService poAgreementLineService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    private MasterDataCommonService masterDataCommonService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HrCommonService hrCommonService;
    @Autowired
    private ActivitiService activitiService;
    @Autowired
    private TaskSubService taskSubService;
    @Autowired
    private TaskService taskService;


    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getPoLineList");
    }
    /**
     * 跳转到合同补充列表
     */
    @RequestMapping("getPoLineList")
    public String getPoAgreementLineList(Pages pages, PoAgreementLineCO poAgreementLineCO, Model model) {
        //分页查询数据
        if (pages.getPage() == 0) {
            pages.setPage(1);
        }
        //分页查询数据
        List<PoAgreementLineBaseVO> list = this.poAgreementLineService.getDataObjectsList(" and p.created_by ='"+ShiroUtil.getPrincipal()+"'",pages, poAgreementLineCO);
        //状态
        Map poStatusMap = this.datasetCommonService.getPOAStatus();
        //审批状态
        Map approveStatusMap = this.datasetCommonService.getApproveStatus();
        //页面属性设置
        model.addAttribute("poLineList", list);
        model.addAttribute("pages", pages);
        model.addAttribute("poStatusMap", poStatusMap);
        model.addAttribute("approveStatusMap", approveStatusMap);
        return "basic.jsp?content=poa/poaAppendList";
    }

    /**
     * 跳转到合同补充新增页面
     */
    @RequestMapping("getPoLineAdd")
    public String getPoAgreementLineAdd(PoAgreementLine poAgreementLine, Model model) {
        poAgreementLine.setStatus("NEW");
        //获取审批通过合同map
        Map poAgreementHeadMap = this.poAgreementHeadService.getPoAgreementHeadMap();
        PoAgreementHeadBase poAgreementHead = poAgreementHeadService.getDataObject(poAgreementLine.getPoHeadCode());
        //页面属性设置
        model.addAttribute("poLine", poAgreementLine);
        model.addAttribute("poHeadMap", poAgreementHeadMap);
        return "basic.jsp?content=poa/poaAppendAdd";
    }

    /**
     * 跳转到合同补充编辑页面
     */
    @RequestMapping("getPoLine")
    public String getPoAgreementLine(PoAgreementLine poAgreementLine, Model model) {
        //查询要编辑的数据
        if(poAgreementLine!=null&&poAgreementLine.getPoLineId()!=null) {
            poAgreementLine = this.poAgreementLineService.getDataObject(poAgreementLine.getPoLineId());
        }
        //获取审批通过合同map
        Map poAgreementHeadMap = this.poAgreementHeadService.getPoAgreementHeadMap();
        //页面属性设置
        model.addAttribute("poLine", poAgreementLine);
        model.addAttribute("poHeadMap", poAgreementHeadMap);
        return "basic.jsp?content=poa/poaAppendEdit";
    }

    /**
     * 跳转合同补充查看页面
     */
    @RequestMapping("getPoLineView")
    public String getPoLineView(PoAgreementLine poAgreementLine, Model model) {
        //查询数据
        poAgreementLine = this.poAgreementLineService.getDataObject(poAgreementLine.getPoLineId());
        if (poAgreementLine != null) {
            if(poAgreementLine.getProcessInstanceId()!=null){
                //根据流程id获取流程审批信息
                List<Activiti_SubTaskInfoRO> activiti_subTaskInfoList = taskSubService.getDataObjects(poAgreementLine.getProcessInstanceId());
                model.addAttribute("subTaskInfoList", activiti_subTaskInfoList);
            }
        }
        //获取审批通过合同map
        Map poAgreementHeadMap = this.poAgreementHeadService.getPoAgreementHeadMap();
        //页面属性设置
        model.addAttribute("poLine", poAgreementLine);
        model.addAttribute("poHeadMap", poAgreementHeadMap);
        return "basic.jsp?content=poa/poaAppendView";
    }

    /**
     * 编辑合同补充信息
     */
    @RequestMapping("editPoLine")
    public String editPoAgreementLine(@Valid PoAgreementLine poAgreementLine,String nextapproverid, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        //参数校验
        Map<String, String> errorMap = this.validateParameters(bindingResult, model);
        if (errorMap.size() > 0) {
            return "forward:getPoHead";
        }
        try {
            boolean isAdd = true;//是否是添加操作
            if(poAgreementLine.getPoLineId()!=null && !"".equals(poAgreementLine.getPoLineId())){ isAdd=false;}
            //保存编辑的数据
            if (isAdd) {
                poAgreementLine.setCreatedDate(new Date());
            }
            this.poAgreementLineService.insertOrUpdateDataObject(poAgreementLine);
            if (isAdd) {
                //获取当前用户职员信息
                HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
                HrDepartment hrDepartmentget=this.hrCommonService.getHrDepartmentParentCompany(staffInfo.getDepartmentCode());
                staffInfo.setCompanyName(hrDepartmentget.getDepartmentName());
                staffInfo.setCompanyCode(hrDepartmentget.getDepartmentCode());
                Map params = new HashMap<String, Object>();
                params.put("panen", staffInfo.getStaffCode());//发起人
                params.put("flzgsp_id_list", this.activitiService.getStaffByPosition("SPB","298"));//法律主管审批
                if("0".equals(staffInfo.getIscompany())){
                    params.put("bmfzr_id_list", this.activitiService.getStaffByPosition(staffInfo.getDepartmentCode(),"290"));//单位/部门负责人审批
                }else{
                    params.put("bmfzr_id_list", this.activitiService.getStaffByPosition(staffInfo.getDepartmentCode(),"291"));//单位/部门负责人审批
                }
                params.put("fgkjsp_id_list", Arrays.asList(nextapproverid.split(",")));//分管会计审批
                params.put("htzgsp_id_list", this.activitiService.getStaffByPosition("SPB","289"));//合同主管审批
                params.put("htglbmfzr_id_list", this.activitiService.getStaffByPosition("SPB","300"));//合同主管审批
                params.put("gszyldsp_id_list", this.activitiService.getStaffByPosition("SPB","302"));//公司主要领导审批
                params.put("gsdwsjsp_id_list", this.activitiService.getStaffByPosition("SPB","303"));//公司党委书记审批

                //启动流程
                ProcessInstance processInstance = activitiService.erpStartProcessInstance(CommonUtils.PROCESS_APPEND_KEY,"web/poAgreementHeadAppend/getPoLineApproval?poLineId="+poAgreementLine.getPoLineId(),params,CommonUtils.ACTIVITI_AGREEMENT_BUS_ID);
                //更新流程实例id
                poAgreementLine.setProcessInstanceId(processInstance.getProcessInstanceId());
                //更新审核状态
                poAgreementLine.setApproveStatus("SUBMIT");
                this.poAgreementLineService.updateDataObject(poAgreementLine);
                //流程发起者完成当前任务节点
                Task task = activitiService.erpFindPersonalTaskByPid(processInstance.getProcessInstanceId());
                if(task != null) {
                    activitiService.erpCompletTask(task.getId(), null, null);
                }
                //保存审批结果和意见
                this.poAgreementHeadService.saveActivitiTaskInfo(poAgreementLine.getPoName()+"(合同补充)",staffInfo,task,processInstance,"1");
                this.poAgreementHeadService.saveSubActivitiTaskInfo(staffInfo,task,processInstance,"1","1",staffInfo.getStaffName()+"发起合同补充");
            }
            attr.addFlashAttribute("hint", "success");
            /*attr.addAttribute("poHeadCode", poAgreementHead.getPoHeadCode());*/
        } catch (Exception e) {
            if (e.getCause().getClass() == ConstraintViolationException.class) {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                return "redirect:getPoLineList";
            } else {
                throw e;
            }
        }
        return "redirect:getPoLineList";
    }


    /**
     * 跳转合同补充流程审批界面
     * id 是任务id（taskid）
     */
    @RequestMapping("getPoLineApproval")
    public String getPoLineApproval(PoAgreementLine poAgreementLine,String id, Model model) {
        //查询数据
        poAgreementLine = this.poAgreementLineService.getDataObject(poAgreementLine.getPoLineId());
        if(poAgreementLine.getProcessInstanceId()!=null){
            //根据流程id获取流程审批信息
            List<Activiti_SubTaskInfoRO> activiti_subTaskInfoList = taskSubService.getDataObjects(poAgreementLine.getProcessInstanceId());
            model.addAttribute("subTaskInfoList", activiti_subTaskInfoList);
        }
        //获取审批通过合同map
        Map poAgreementHeadMap = this.poAgreementHeadService.getPoAgreementHeadMap();
        Task task = taskService.createTaskQuery().taskId(id).singleResult();//获取流程代办任务
        if("合同主管审批".equals(task.getName())){
            model.addAttribute("selectShow", 1);
        }
        //页面属性设置
        model.addAttribute("poLine", poAgreementLine);
        model.addAttribute("poHeadMap", poAgreementHeadMap);
        model.addAttribute("taskId", id);
        return "basic.jsp?content=poa/poaAppendApproval";
    }

    /**
     * 删除合同补充数据
     */
    @RequestMapping("deletePoLine")
    public String deletePoAgreementLine(PoAgreementLine poAgreementLine, RedirectAttributes attr) {
        //删除数据前验证数据
        if (poAgreementLine != null && poAgreementLine.getPoLineId() != null && StringUtils.isNotBlank(poAgreementLine.getPoHeadCode())) {
            if (poAgreementLine.getStatus().equals("NEW")) {
                PoAgreementLineBase poAgreementLineTemp = this.poAgreementLineService.getDataObject(poAgreementLine.getPoLineId());
                //删除数据
                this.poAgreementLineService.deleteDataObject(poAgreementLine);
                if(poAgreementLineTemp.getProcessInstanceId() != null && !"".equals(poAgreementLineTemp.getProcessInstanceId())){
                    this.activitiService.deleteProcessInstance(poAgreementLineTemp.getProcessInstanceId());
                }
                //提示信息
                attr.addFlashAttribute("hint", "success");
            } else {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", "非新建状态不能删除");
            }
        }
        return "redirect:getPoLineList";
    }

    /**
     * 跳转流程任务列表界面
     */
    @RequestMapping("todoPage")
    public String todoPage(Model model) {
        //获取当前用户职员信息
        HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
        //List<TaskVo> tasklist  = activitiService.erpFindPersonalTaskList(staffInfo);
        List<TaskVo> tasklist =this.activitiService.queryTaskInfo(this.activitiService.erpFindPersonalTaskList(staffInfo));

        //页面属性设置
        model.addAttribute("tasklist", tasklist);
        return "basic.jsp?content=activitiPage/todoPage";
    }

    /**
     * 完成流程代办任务
     */
    @RequestMapping("doCompletTask")
    public String doCompletTask(String tab,String taskId,String processInstanceId,String nextapproverid,String nextapproverid1,String poHeadCode,String result, String content, Model model) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if(task != null){
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            Map<String,String> nextapproverids = new HashMap<>();
            if(nextapproverid !=null && nextapproverid1 != null){
                nextapproverids.put("znbmfzr_id_list",nextapproverid);
                nextapproverids.put("fgldsp_id_list",nextapproverid1);
            }
            activitiService.erpCompletTask(taskId,result,nextapproverids);
            //获取当前用户职员信息
            HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
            HrDepartment hrDepartmentget=this.hrCommonService.getHrDepartmentParentCompany(staffInfo.getDepartmentCode());
            staffInfo.setCompanyName(hrDepartmentget.getDepartmentName());
            staffInfo.setCompanyCode(hrDepartmentget.getDepartmentCode());
            //判断流程是否结束
            ProcessInstance processInstance1 = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            if(processInstance1==null){
                //更新表单的状态（审核中-->审核完成）
                this.poAgreementLineService.updateStatus(poHeadCode,"CONFIRM");
                this.poAgreementLineService.updateApproveStatus(poHeadCode, "COMPLETE");
                this.poAgreementHeadService.saveSubActivitiTaskInfo(staffInfo,task,processInstance,"4",result,content);//状态  1-待审批 2-审批中 3-驳回 4-完成
            }else{
                //判断流程审批是否驳回
                if("0".equals(result)){
                    this.poAgreementLineService.updateApproveStatus(poHeadCode, "REJECT");
                    this.poAgreementHeadService.saveSubActivitiTaskInfo(staffInfo,task,processInstance,"3",result,content);
                }else{
                    this.poAgreementLineService.updateApproveStatus(poHeadCode, "APPROVE");
                    this.poAgreementHeadService.saveSubActivitiTaskInfo(staffInfo,task,processInstance,"2",result,content);
                }
            }
        }
        return "redirect:todoPage";
    }

    /**
     * 根据编码查询合同信息
     */
    @ResponseBody
    @RequestMapping("getPoHeadByCode")
    public PoAgreementHeadBase getPoAgreementHead(PoAgreementHeadBase poAgreementHeadBase) {
        PoAgreementHeadBase poAgreementHead = poAgreementHeadService.getDataObject(poAgreementHeadBase.getPoHeadCode());
        return poAgreementHead;
    }

}
